import EchartsWrap from '@/components/widgets/EchartsWrap';
import React, { useState, useEffect } from 'react';
import styles from './index.less';
import { EChartOption } from 'echarts';
import { fill as _fill } from 'lodash';
import cls from 'classnames';
import { getPplData } from './processingPplData';

const center = ['50%', '50%'];

const barWidth = 3;
const barGap = 8;
const barStart = 18;

let colors = ['#2FB0FF', '#2F78FF', '#2F35FF', '#2FFF9F', '#2FF3FF', '#802FFF'];

let legendFormaterTable = {};

const option: EChartOption = {
  backgroundColor: 'transparent',
  tooltip: {
    show: true,
  },
  color: colors,

  grid: {
    top: '80',
    left: '36',
    bottom: '15',
    right: '45',
    // containLabel: true,
  },
  legend: {
    // show: true,
    show: false,
    icon: 'stack',
    itemWidth: 8,
    itemHeight: 2,
    top: 200,
    left: 0,
    // orient: 'vertical',
    textStyle: {
      color: 'rgba(255,255,255, .7)',
      fontSize: 12,
      rich: {
        // value: {
        //   fontSize: 12,
        //   fontWeight: '400',
        //   color: '#fff',
        // },
        // name: {
        //   fontFamily: 'monospace',
        //   fontSize: 12,
        //   fontWeight: '300',
        //   color: 'rgba(255, 255, 255, 0.5)',
        // },
      },
    },
    // formatter(str) {
    //   let result = `{name|${str}}`;
    //   if (legendFormaterTable[str]) {
    //     const MAX_LEGEND_LEN = 8;
    //     let spaceNum = MAX_LEGEND_LEN - str.length;
    //     let spaceStr = _fill(Array(spaceNum), ' ').join('');
    //     result = `{name|${str + spaceStr}}` + `{value|${legendFormaterTable[str]}}`;
    //   }
    //   return result;
    // },
  },
  series: [
    {
      // name: nameArr[i],
      type: 'pie',
      startAngle: 90,
      radius: ['60%', '70%'],
      hoverAnimation: false,
      center,
      label: false,
      clockwise: false,
      data: [],
    },
  ],
};

const WorkingPpl = () => {
  const [curData, setCurData] = useState(option);
  const [isShowMore, setIsShowMore] = useState(false);
  const [legendExtraData, setLegendExtraData] = useState([]);

  const [restData, setRestData] = useState([]);
  const [peopleInfoFakeData, setPeopleInfoFakeData] = useState([]);

  useEffect(() => {
    if (!peopleInfoFakeData.length) {
      return;
    }
    // if (!workingPpl.length) return;
    let newOption = JSON.parse(JSON.stringify(option));
    const [nameArr, workingNumArr, nonWorkingNumArr] = peopleInfoFakeData;
    // let series: EChartOption.Series = [];
    for (let i = 0; i < nameArr.length; i++) {
      const color = colors[i];
      legendFormaterTable[nameArr[i]] = workingNumArr[i];
      newOption.series[0].data.push(
        {
          value: workingNumArr[i],
          name: nameArr[i],
          itemStyle: {
            normal: {
              color,
            },
          },
        },
        {
          value: 1,
          tooltip: false,
          // name: '不在岗',
          itemStyle: {
            normal: {
              color: 'rgba(0,0,0,0)',
            },
          },
        },
      );
    }
    // newOption.series = series;
    newOption.legend.data = nameArr;
    console.log(newOption);
    setTimeout(() => {
      setCurData(newOption);
    }, 400);

    setLegendExtraData(
      workingNumArr.map((num, i) => {
        return {
          num,
          title: nameArr[i],
          color: colors[i],
        };
      }) || [],
    );
  }, [restData, peopleInfoFakeData]);

  useEffect(() => {
    getRealData();
  }, []);

  async function getRealData() {
    const [fullData, _chartData, _restData] = await getPplData();
    setRestData(_restData);
    setPeopleInfoFakeData(_chartData);
  }

  const renderItem = pplList => {
    return pplList.map(([name, full, online]) => {
      const offLine = full - online;
      return (
        <div className={cls(styles.deviceStateItemWrap)} key={name}>
          <div className={cls(styles.deviceStateItem)}>
            <div className={cls(styles.deviceStateTitle)}>
              <a href="javascript:void(0)" className={styles.name}>
                {name}
              </a>
              <div className={styles.nameNumber}>{full}</div>
            </div>
            <div className={cls(styles.deviceStateContent)}>
              <div>
                <span className={cls(styles.deviceStateContentName)}>进场</span>
                <span className={cls(styles.deviceStateContentValue)}> {online}</span>
              </div>
              <div>
                <span className={cls(styles.deviceStateContentName)}>离场</span>
                <span className={cls(styles.deviceStateContentValue1)}>{offLine}</span>
              </div>
            </div>

            <div className={cls(styles.deviceChart)}>
              <div
                className={cls(styles.deviceChartL)}
                style={{ width: (online / full) * 100 + '%' }}
              ></div>
              <div
                className={cls(styles.deviceChartR)}
                style={{ width: (offLine / full) * 100 + '%' }}
              ></div>
            </div>
          </div>
        </div>
      );
    });
  };

  return (
    <div className={styles.peopleInfo} style={{ marginTop: 24 }}>
      <p className={styles.title}>
        <div className="side-panel2-subtitle">
          <a href="http://223.112.163.214:8100/" target="_blank">
            人员管理
          </a>
        </div>

        {/* <span className={styles.titleBtn} onClick={() => setIsShowMore(e => !e)}>
          {isShowMore ? '收起' : '更多'}
        </span> */}
      </p>

      <div className={styles.chartBg}>
        <div className={styles.img} />
        <EchartsWrap
          option={curData}
          opts={{ height: 180 }}
          style={{ height: 'auto', width: '322px' }}
          // className={styles.overflowY}
        />
      </div>
      <ul className={styles.legendExtra}>
        {!!legendExtraData.length &&
          legendExtraData.map(({ num, title, color }, i) => {
            return (
              <li key={i}>
                <p>
                  <span style={{ background: color }}></span>
                  {title}
                </p>
                {num}
              </li>
            );
          })}
      </ul>
      <div className={cls(styles.deviceStateWrap)}>{isShowMore && renderItem(restData)}</div>
    </div>
  );
};

export default WorkingPpl;
